package com.example.friend.mvp.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.friend.R;
import com.example.friend.R.menu;
import com.example.friend.mvp.model.ChildCircleModel;
import com.example.friend.mvp.model.CircleModel;
import com.example.friend.mvp.ui.adapter.CircleAdapter;
import com.example.friend.mvp.ui.adapter.RecyclerViewWithContextMenu;
import com.example.friend.mvp.ui.adapter.UserAdapter;
import com.github.ielse.imagewatcher.ImageWatcherHelper;
import com.h.cheng.pselector.base.load.PSConfig;
import com.h.cheng.pselector.base.load.PSManager;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

import static com.example.friend.R.drawable;
import static com.example.friend.R.id;
import static com.example.friend.R.layout;
import static com.example.friend.R.menu;

/**
 * @author: admins
 * date:   2019/6/26 18:02
 * desc:   朋友圈
 */
public class CircleActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
    private CircleAdapter circleAdapter;
    private List<CircleModel> mList;
    private RecyclerView recyclerView;
    private TextView tvTitle;
    private Toolbar toolbar;
    private ImageView ivPhoto, ivUser;
    private static final int RC_STORAGE = 1001;
    private PopupWindow mMorePopupWindow;
    private int mWidth;
    private int mHeight;
    private TextView tvCommon;
    private List<ChildCircleModel> circleModelList;
    private List<ChildCircleModel> textModels;
    private List<ChildCircleModel> oneModels;
    private List<ChildCircleModel> twoModels;
    private List<ChildCircleModel> videoModels;
    public ImageWatcherHelper iwHelper;


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(layout.ac_circle);
        initView();
        initListener();
        registerForContextMenu(recyclerView);
    }

    private void requestPermision() {
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // Already have permission, do the thing
            try {
                taskPhoto();
            } catch (Exception e) {
                e.printStackTrace();
            }
            // ...
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "我们的APP需求需要以下权限，请您打开",
                    RC_STORAGE, perms);
        }
    }

    private void initView() {
        recyclerView = findViewById(id.rv_circle);
        tvTitle = findViewById(id.tv_title);
        toolbar = findViewById(id.toolbar);
        ivPhoto = findViewById(id.iv_right);
        ivUser = findViewById(id.iv_user);
        tvTitle.setText("朋友圈");
        ivPhoto.setImageDrawable(getResources().getDrawable(drawable.ic_photo_camera_black_24dp));
        initAdapter();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void initListener() {
        toolbar.setNavigationIcon(drawable.ic_arrow_back_black_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //长按发送文字
        ivPhoto.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                startActivity(new Intent(CircleActivity.this, SendTextActivity.class));
                return false;
            }
        });
        ivPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPermision();
            }
        });
        ivUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(CircleActivity.this,RecyclerViewWithContenMenuActivity.class));
            }
        });
    }


    private void initAdapter() {
        mList = new ArrayList<>();
        circleModelList = new ArrayList<>();
        ChildCircleModel childCircleModel = new ChildCircleModel(1);
        childCircleModel.setImg("1");
        circleModelList.add(childCircleModel);

        textModels = new ArrayList<>();
        ChildCircleModel textModel = new ChildCircleModel(2);
        textModel.setAddress("西安市未央区文景二路");
        textModel.setText("来看看");
        textModels.add(textModel);

        oneModels = new ArrayList<>();
        ChildCircleModel oneModel = new ChildCircleModel(3);
        oneModel.setImg("2");
        oneModel.setText("张甜甜演艺~~山西火开播了，快去他的直播间看看吧");
        oneModels.add(oneModel);

        twoModels = new ArrayList<>();
        ChildCircleModel twoModel = new ChildCircleModel(4);
        twoModel.setImg("3");
        twoModels.add(twoModel);

        videoModels = new ArrayList<>();
        ChildCircleModel videoModel = new ChildCircleModel(5);
        videoModel.setUrl("http://v.ysbang.cn/data/video/2015/rkb/2015rkb01.mp4");
        videoModels.add(videoModel);

        for (int i = 0; i < 10; i++) {
            CircleModel circleModel = new CircleModel();
            circleModel.setContent("今天天气很热");
            circleModel.setName("灰太狼");
            circleModel.setLevel("新手");
            circleModel.setList(circleModelList);
/*            circleModel.setList(textModels);
            circleModel.setList(oneModels);
            circleModel.setList(twoModels);
            circleModel.setList(videoModels);*/
            mList.add(circleModel);
        }

        circleAdapter = new CircleAdapter(mList);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(circleAdapter);

        circleAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == id.tv_common) {
                    tvCommon = findViewById(R.id.tv_common);
                    showMore(view);
                }
                if(view.getId() == id.iv_user){
                    final List<String> longPictureList = new ArrayList<>();
                    longPictureList.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1536811355543&di=87e5c3def99fdad3e356263114f11f0b&imgtype=0&src=http%3A%2F%2Fthumb11.jfcdns.com%2Fthumb%2F2017-11%2Fbce5a02c4551db77_600_400.jpeg");
                    longPictureList.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1536811355543&di=a0dbe4cb9420b031669693f2d170aaae&imgtype=0&src=http%3A%2F%2Fthumb10.jfcdns.com%2Fthumb%2F2017-11%2Fbce5a02c45735cc6_600_400.jpeg");
                    longPictureList.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1536811355543&di=a1b77f149342811754180a7b88382e13&imgtype=0&src=http%3A%2F%2Fgss0.bdstatic.com%2F7LsWdDW5_xN3otebn9fN2DJv%2Fdoc%2Fpic%2Fitem%2Ff31fbe096b63f62442fe1e3b8b44ebf81a4ca362.jpg");
                    longPictureList.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1536811355545&di=2436088f354f1a8355ea8db0a82592e0&imgtype=0&src=http%3A%2F%2Fgss0.bdstatic.com%2F7LsWdDW5_xN3otebn9fN2DJv%2Fdoc%2Fpic%2Fitem%2F3801213fb80e7bec392a30d9232eb9389b506b11.jpg");
                    final int initPosition = 0;
                    final SparseArray<ImageView> mappingViews = new SparseArray<>();
                    mappingViews.put(initPosition, (ImageView) view);
                    iwHelper.show(initPosition, mappingViews, converts(longPictureList));
                }
            }
        });
    }

    private void showMore(View view) {
        if (mMorePopupWindow == null) {
            LayoutInflater li = (LayoutInflater) CircleActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View content = li.inflate(layout.layout_more, null, false);
            mMorePopupWindow = new PopupWindow(content, ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            mMorePopupWindow.setBackgroundDrawable(new BitmapDrawable());
            mMorePopupWindow.setOutsideTouchable(true);
            mMorePopupWindow.setTouchable(true);
            content.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            mWidth = content.getMeasuredWidth();
            mHeight = content.getMeasuredHeight();
            View parent = mMorePopupWindow.getContentView();
            TextView like = (TextView) parent.findViewById(id.like);
            TextView comment = (TextView) parent.findViewById(id.comment);
            // 点赞的监听器
            like.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final AlertDialog.Builder alert = new AlertDialog.Builder(CircleActivity.this);
                    alert.setTitle("点赞");
                    alert.setNegativeButton("取消", null);
                    alert.show();
                    mMorePopupWindow.dismiss();
                }
            });

            // 评论的监听器
            comment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final AlertDialog.Builder alert = new AlertDialog.Builder(CircleActivity.this);
                    alert.setTitle("评论");
                    alert.setNegativeButton("取消", null);
                    alert.show();
                    mMorePopupWindow.dismiss();
                }
            });
        }

        if (mMorePopupWindow.isShowing()) {
            mMorePopupWindow.dismiss();
        } else {
           int heightMoreBtnView = view.getHeight();

            mMorePopupWindow.showAsDropDown(view, -mWidth, -(mHeight + heightMoreBtnView) / 2);
        }
    }

    private void taskPhoto() {
        PSConfig config = new PSConfig().setUseSysAlbum(true);
        PSManager.of(config).forDialog(CircleActivity.this, ivPhoto);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    public List<Uri> converts(List<String> data) {
        List<Uri> list = new ArrayList<>();
        for (String d : data) list.add(Uri.parse(d));
        return list;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        // Some permissions have been granted
        try {
            taskPhoto();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        // Some permissions have been denied
    }



    public void CreateMenu(Menu menu)
    {
        int groupID = 0;
        int order = 0;
        int[] itemID = {1,2};

        for(int i=0;i<itemID.length;i++)
        {
            switch(itemID[i])
            {
                case 1:
                    menu.add(groupID, itemID[i], order, "编辑");
                    break;
                case 2:
                    menu.add(groupID, itemID[i], order, "删除");
                    break;
                default:
                    break;
            }
        }
    }
}
